package com.nowcoder.code.hjnc;

import com.algorithm.model.ListNode;

public class NC70 {

    public ListNode sortInList(ListNode head) {
        return sortList(head);
    }

    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode l1 = head;
        ListNode l2 = head.next;

        while (l2 != null && l2.next != null) {
            l1 = l1.next;
            l2 = l2.next.next;
        }

        ListNode mid = l1.next;
        l1.next = null;
        l1 = sortList(head);
        l2 = sortList(mid);

        ListNode node = new ListNode(0);
        ListNode ans = node;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                node.next = l1;
                l1 = l1.next;
            } else {
                node.next = l2;
                l2 = l2.next;
            }
            node = node.next;
        }
        node.next = l1 != null ? l1 : l2;
        return ans.next;
    }

}
